import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Checkbox, Card, Spin, message, Table} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, PAGE, TABLE, FIXED_COLUMN_WIDTH, DATE_FORMAT} from '../constants';
import {conventEnumValueToString, formatAmount, formatDateTime} from '../utils';
import {PERMISSION} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import styles from './style.css';
import {validateAdd, renderBoolean} from './utils';
import Return from '../common/Return';
import PartSelectPanel from './PartSelectPanel';
import PartAssistPanel from './PartAssistPanel';
import WorkItemTablePanel from './WorkItemTablePanel';
import WorkItemSelectPanel from './WorkItemSelectPanel';
import DutyUnit from '../common/DutyUnitSelect/SelectEdit';
import {dutyUnitType, repairType, currency} from '../Enum';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
const supplierCondition = {
    type: dutyUnitType.索赔供应商,
};
const dutyUnitCondition = {
    type: dutyUnitType.责任单位,
};
const width = {
    width: '100%'
};
export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPanel: false,
        showPart: false,
        showWorkItem: false
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    };

    showPart = () => {
        this.setState({
            showPart: !this.state.showPart
        });
    };

    onSubmit = () => {
        const result = validateAdd(this.props.conditions);
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    onClickAddAccessory = () => {
        this.setState({
            hasOperat: true,
            showPanel: true,
        });
    }

    onClickAddPart = () => {
        this.setState({
            hasOperat: true,
            showPart: true
        });
    }

    onDeletePart = e => {
        const {id} = e.target.dataset;
        this.setState({
            hasOperat: true,
        });
        this.props.onDeletePart(id);
    }

    onDeleteAllPart = () => {
        this.setState({
            hasOperat: true,
        });
        this.props.onDeleteAllPart();
    }

    onDeleteAccessoryPart = e => {
        const {id} = e.target.dataset;
        this.setState({
            hasOperat: true,
        });
        this.props.onDeleteAccessoryPart(id);
    }

    onDeleteAllAccessoryPart = () => {
        this.setState({
            hasOperat: true,
        });
        this.props.onDeleteAllAccessoryPart();
    }


    onChangeQty = (value, id) => {
        this.setState({
            hasOperat: true,
        });
        this.props.onUpdatePart({
            id,
            quantity: value,
        });
    }

    onChangeAccessQty = (value, id) => {
        this.setState({
            hasOperat: true,
        });
        this.props.onUpdateAccessoryPart({
            id,
            quantity: value,
        });
    }
    
    onSelectPart = data => {
        this.setState({showPart: false});
        this.props.onSelectPart(data);
        this.props.onSelectWorkItem(data);
    }

    onSelectAccessory = data => {
        this.setState({showPanel: false});
        this.props.onSelectAccessory(data);
    }
    onSelectAccessory = data => {
        this.setState({showPanel: false});
        this.props.onSelectAccessory(data);
    }

    onSelectSupplier = data => {
        this.setState({
            hasOperat: true,
        });
        this.props.onSelectSupplier(data);
    }
    onSelectDutyUnit = data => {
        this.setState({
            hasOperat: true,
        });
        this.props.onSelectDutyUnit(data);
    }

    onChangeBox = e => {
        const {checked, id} = e.target;
        this.setState({
            hasOperat: true,
        });
        this.props.onChangeCause(id, checked);
    }
    onDeleteWorkItem = id => {
        this.setState({
            hasOperat: true,
        });
        this.props.onDeleteWorkItem(id);
    };
    onDeleteAllWorkItem = () => {
        this.setState({
            hasOperat: true,
        });
        this.props.onDeleteAllWorkItem();
    };
    onWorkItemLaborHourChange = (id, value) => {
        this.setState({
            hasOperat: true,
        });
        this.props.onUpdateWorkItemlaborHour({
            id,
            laborHour: value,
        });
    }
    onWorkItemLaborPriceChange = (id, value) => {
        this.setState({
            hasOperat: true,
        });
        this.props.onUpdateWorkItemlaborPrice({
            id,
            laborPrice: value,
        });
    }
    onClickAddWorkItem = e => {
        e.stopPropagation();
        const {details = []} = this.props.conditions;
        if(!details.some(d => d.isCaused === true))
            return message.warning(this.props.intl.formatMessage({
                id: 'validator.message.isCaused',
                defaultMessage: '请选择一个材料为主损件'
            }));
        this.setState({showWorkItem: true});
    }
    onCloseWorkItem = () => {
        this.setState({showWorkItem: false});
    }
    onSelectWorkItem = data => {
        this.setState({showWorkItem: false});
        this.props.onSelectWorkItemQuery(data);
    }

    render() {
        const {details = [], accessoryDetails = [], workItemDetails = []} = this.props.conditions;
        const partIds = details.map(v => v.usedPartId);
        const columnMaterials = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.usedPartCode',
                    defaultMessage: '旧件编号'
                }),
                dataIndex: 'usedPartCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.usedPartName',
                    defaultMessage: '旧件名称'
                }),
                dataIndex: 'usedPartName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.isCaused',
                    defaultMessage: '是否主损件'
                }),
                dataIndex: 'isCaused',
                render: (text, record) => (
                    <FormItem>
                        <Checkbox id={record.usedPartId} checked={record.isCaused} onChange={this.onChangeBox} />
                    </FormItem>
                )
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.unit',
                    defaultMessage: '计量单位'
                }),
                dataIndex: 'unit'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
                render: (text, record) => (
                    <FormItem validateStatus={this.state.isValidate && !record.quantity ? 'error' : null}
                        required>
                        <LocalizeInputNumber
                            min={0}
                            precision={record.isDecimalAllowed ? 3 : 0}
                            style={width}
                            id={record.usedPartId}
                            value={record.quantity}
                            onChange={this.onChangeQty} />
                    </FormItem>
                )
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialTablePanel.materialFee',
                    defaultMessage: '材料费合计'
                }),
                dataIndex: 'materialFee',
                className: styles.textAlign,
                render: (text, record) => {
                    const {price = 0, quantity = 0} = record;
                    return formatAmount(price * quantity);
                }
            },

            {
                title: details.length ? (
                    <WrappedPopconfirm
                        id="delete"
                        title={this.props.intl.formatMessage({
                            id: 'add.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.props.onDeleteAllPart}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'add.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onDeletePart} key="delete" data-id={record.usedPartId} data-applyid={record.claimId}>
                    {this.props.intl.formatMessage({
                        id: 'add.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            }
        ];
        const colums = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.usedPartCode',
                    defaultMessage: '旧件编号'
                }),
                dataIndex: 'usedPartCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.usedPartName',
                    defaultMessage: '旧件名称'
                }),
                dataIndex: 'usedPartName'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.unit',
                    defaultMessage: '计量单位'
                }),
                dataIndex: 'unit'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
                render: (text, record) => (
                    <FormItem validateStatus={this.state.isValidate && !record.quantity ? 'error' : null}
                        required>
                        <LocalizeInputNumber
                            min={0}
                            precision={record.isDecimalAllowed ? 3 : 0}
                            style={width}
                            id={record.usedPartId}
                            value={record.quantity}
                            onChange={this.onChangeAccessQty} />
                    </FormItem>
                )
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.materialFee',
                    defaultMessage: '辅料费合计'
                }),
                dataIndex: 'materialFee',
                className: styles.textAlign,
                render: (text, record) => {
                    const {price = 0, quantity = 0} = record;
                    return formatAmount(price * quantity);
                }
            },
            {
                title: details.length ? (
                    <WrappedPopconfirm
                        id="delete"
                        title={this.props.intl.formatMessage({
                            id: 'add.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'add.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.props.onDeleteAllAccessoryPart}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'add.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onDeleteAccessoryPart} key="delete" data-id={record.usedPartId} data-applyid={record.claimId}>
                    {this.props.intl.formatMessage({
                        id: 'add.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            }
        ];

        const supplierInfo = this.props.conditions.supplierId ? {
            id: this.props.conditions.supplierId,
            code: this.props.conditions.supplierCode,
            name: this.props.conditions.supplierName
        } : null;
        const dutyUnitInfo = this.props.conditions.dutyUnitId ? {
            id: this.props.conditions.dutyUnitId,
            code: this.props.conditions.dutyUnitCode,
            name: this.props.conditions.dutyUnitName
        } : null;
        
        return (
            <div className={styles.detail}>
                {this.state.showPart && <PartSelectPanel
                    brandId={this.props.conditions.brandId}
                    dealerId={this.props.conditions.dealerId}
                    repairDate={this.props.conditions.repairDate}
                    productCategoryCode={this.props.conditions.productCategoryCode}
                    currentSelectRowkeys={details}
                    onSelect={this.onSelectPart}
                    onCancel={this.showPart} />}
                {this.state.showPanel && <PartAssistPanel
                    brandId={this.props.conditions.brandId}
                    dealerId={this.props.conditions.dealerId}
                    currentSelectRowkeys={accessoryDetails}
                    selectKey={this.props.conditions.id}
                    partIds={partIds}
                    repairDate={this.props.conditions.repairDate}
                    productCategoryCode={this.props.conditions.productCategoryCode}
                    onSelect={this.onSelectAccessory}
                    onCancel={this.showPanel} />}
                    
                {
                    this.state.showWorkItem &&
                    <WorkItemSelectPanel
                        currentSelectRowkeys={workItemDetails}
                        brandId={this.props.conditions.brandId}
                        productCategoryCode={this.props.conditions.productCategoryCode}
                        selectKey={this.props.conditions.id}
                        onCancel={this.onCloseWorkItem}
                        onSelect={this.onSelectWorkItem} />
                }
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card title={this.props.intl.formatMessage({
                            id: 'add.order.title',
                            defaultMessage: '单据信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.supplierId ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.supplierId',
                                            defaultMessage: '供应商'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <DutyUnit
                                            value={supplierInfo}
                                            allowClear={false}
                                            conditions={supplierCondition}
                                            onSelect={this.onSelectSupplier} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.dutyUnitId ? 'error' : null}
                                        required
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.dutyUnitId',
                                            defaultMessage: '责任单位'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <DutyUnit
                                            value={dutyUnitInfo}
                                            allowClear={false}
                                            conditions={dutyUnitCondition}
                                            onSelect={this.onSelectDutyUnit} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.code',
                                    defaultMessage: '索赔单号'
                                })}>{this.props.conditions.code}
                                </FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.claimApplyCode',
                                    defaultMessage: '预授权单号'
                                })}>{this.props.conditions.claimApplyCode}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.brandCode',
                                    defaultMessage: '品牌'
                                })}>{this.props.conditions.brandCode}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.subDealerCode',
                                    defaultMessage: '经销商编号'
                                })}>{this.props.conditions.subDealerCode}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.subDealerName',
                                    defaultMessage: '经销商名称'
                                })}>{this.props.conditions.subDealerName}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.subClaimCode',
                                    defaultMessage: '经销商申请单号'
                                })}>{this.props.conditions.subClaimCode}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.currency',
                                    defaultMessage: '币种'
                                })}>{conventEnumValueToString(currency, this.props.conditions.currency)}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.repairType',
                                    defaultMessage: '索赔类型'
                                })}>{conventEnumValueToString(repairType, this.props.conditions.repairType)}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.faultModeCode',
                                    defaultMessage: '故障原因编号'
                                })}>{this.props.conditions.faultModeCode}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.faultModeName',
                                    defaultMessage: '故障原因名称'
                                })}>{this.props.conditions.faultModeName}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.faultDescription',
                                    defaultMessage: '故障描述'
                                })}>{this.props.conditions.faultDescription}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.isOut',
                                    defaultMessage: '是否外出索赔'
                                })}>{renderBoolean(this.props.conditions.isOut)}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.outFee',
                                    defaultMessage: '外出费'
                                })}>{formatAmount(this.props.conditions.outFee)}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.partPurchasedDate',
                                    defaultMessage: '自费购件时间'
                                })}>{formatDateTime(this.props.conditions.partPurchasedDate, DATE_FORMAT)}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.repairCode',
                                    defaultMessage: '维修单号'
                                })}>{this.props.conditions.repairCode}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.shipmentPort',
                                    defaultMessage: '维修日期'
                                })}>{formatDateTime(this.props.conditions.repairDate, DATE_FORMAT)}</FormItem></Col>
                            </Row>

                        </Card>
                        <Card
                            className={styles.marginBottom} title={this.props.intl.formatMessage({
                                id: 'add.customer.title',
                                defaultMessage: '客户信息'
                            })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.vin',
                                    defaultMessage: 'VIN'
                                })}>{this.props.conditions.vin}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.mileage',
                                    defaultMessage: '行驶里程'
                                })}>{this.props.conditions.mileage}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.engineCode',
                                    defaultMessage: '发动机号'
                                })}>{this.props.conditions.engineCode}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.customerName',
                                    defaultMessage: '用户姓名'
                                })}>{this.props.conditions.customerName}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.cellPhoneNumber',
                                    defaultMessage: '用户电话'
                                })}>{this.props.conditions.cellPhoneNumber}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.saleDate',
                                    defaultMessage: '实销日期'
                                })}>{formatDateTime(this.props.conditions.saleDate, DATE_FORMAT)}</FormItem></Col>
                                <Col {...FORM_OPTIONS.col}><FormItem {...FORM_OPTIONS.item} label={this.props.intl.formatMessage({
                                    id: 'add.operation.shippingDate',
                                    defaultMessage: '发车日期'
                                })}>{formatDateTime(this.props.conditions.shippingDate, DATE_FORMAT)}</FormItem></Col>
                            </Row>
                        </Card>

                        <Card
                            extra={<Button onClick={this.onClickAddPart} size="small">
                                {this.props.intl.formatMessage({
                                    id: 'add.btn.add',
                                    defaultMessage: '新增'
                                })}
                            </Button>}
                            title={this.props.intl.formatMessage({
                                id: 'add.table.claimMaterialDetails',
                                defaultMessage: '材料清单'
                            })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columnMaterials}
                                rowKey="usedPartId"
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        </Card>
                        <Card
                            extra={<Button onClick={this.onClickAddWorkItem} size="small">
                                {this.props.intl.formatMessage({
                                    id: 'add.btn.newWorkItem',
                                    defaultMessage: '新增项目'
                                })}
                            </Button>}
                            title={this.props.intl.formatMessage({
                                id: 'add.table.workItemDetails',
                                defaultMessage: '项目清单'
                            })}>
                            <WorkItemTablePanel
                                onDeleteWorkItem={this.onDeleteWorkItem}
                                onDeleteAllWorkItem={this.onDeleteAllWorkItem}
                                onWorkItemLaborHourChange={this.onWorkItemLaborHourChange}
                                onWorkItemLaborPriceChange={this.onWorkItemLaborPriceChange}
                                data={workItemDetails}/>
                        </Card>
                        <Card
                            extra={<Button onClick={this.onClickAddAccessory} size="small">
                                {this.props.intl.formatMessage({
                                    id: 'add.btn.add',
                                    defaultMessage: '新增'
                                })}
                            </Button>} title={this.props.intl.formatMessage({
                                id: 'add.table.accessoryDetails',
                                defaultMessage: '辅料清单'
                            })}>
                            <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="usedPartId"
                                pagination={false}
                                dataSource={accessoryDetails}
                                {...TABLE} />
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}
                                            type="primary">
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onDeleteAccessoryPart: PropTypes.func.isRequired,
    onDeleteAllAccessoryPart: PropTypes.func.isRequired,
    onDeleteAllPart: PropTypes.func.isRequired,
    onDeletePart: PropTypes.func.isRequired,
    onSelectAccessory: PropTypes.func.isRequired,
    onSelectDetails: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    onUpdateAccessoryPart: PropTypes.func.isRequired,
    onUpdatePart: PropTypes.func.isRequired,
    intl: PropTypes.object,
    workItem: PropTypes.object,
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onSubmit,
    getDetail,
    deletePart,
    deleteAccessoryPart,
    deleteAllPart,
    deleteAllAccessoryPart,
    updatePart,
    updateAccessoryPart,
    selectAccessoryPart,
    selectDetails,
    selectSupplier,
    selectDutyUnit,
    selectPart,
    changeCause,
    selectWorkItem,
    deleteWorkItem,
    deleteAllWorkItem,
    onSelectWorkItemQuery,
    updateWorkItemlaborHour,
    updateWorkItemlaborPrice,
} from './actions';
import {createSelector} from 'reselect';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        return data.includes(PERMISSION.update) && options.includes(PERMISSION.update);
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
    workItem: state.getIn(['page', 'domainData', 'workItem', 'data']),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id, true)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: () =>
        dispatch(onSubmit(ownProps.id, ownProps.isSubmit)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onDeletePart: id => dispatch(deletePart(id)),
    onDeleteAccessoryPart: id => dispatch(deleteAccessoryPart(id)),
    onDeleteAllPart: () => dispatch(deleteAllPart()),
    onDeleteAllAccessoryPart: () => dispatch(deleteAllAccessoryPart()),
    onUpdatePart: data => dispatch(updatePart(data)),
    onUpdateAccessoryPart: data => dispatch(updateAccessoryPart(data)),
    onSelectAccessory: data => dispatch(selectAccessoryPart(data)),
    onSelectDetails: data => dispatch(selectDetails(data)),
    onSelectSupplier: data => dispatch(selectSupplier(data)),
    onSelectDutyUnit: data => dispatch(selectDutyUnit(data)),
    onSelectPart: data => dispatch(selectPart(data)),
    onChangeCause: (id, value) => dispatch(changeCause(id, value)),
    onSelectWorkItem: data => dispatch(selectWorkItem(data)),
    onDeleteWorkItem: id => dispatch(deleteWorkItem(id)),
    onDeleteAllWorkItem: () => dispatch(deleteAllWorkItem()),
    onSelectWorkItemQuery: data => dispatch(onSelectWorkItemQuery(data)),
    onUpdateWorkItemlaborHour: data => dispatch(updateWorkItemlaborHour(data)),
    onUpdateWorkItemlaborPrice: data => dispatch(updateWorkItemlaborPrice(data)),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
